import Sequelize from "sequelize"
import glob from "glob"
import config from "./config"

class model {
    constructor() {
        this.config = config;
        this.glob = glob;
        // redis配置
        this._initSequelize().then(() => this._getModels())
    }

    async _getModels() {
        this.glob(__dirname + "/models/**.js", async (err, files) => {
            let model = [];
            for (let i of files) {
                model.push(import(i))
            }
            Promise.all(model).then(res => {
                for (let i of res) {
                    this[i.default.options.name.singular] = i.default;
                    if (this[i.default.options.name.singular].associate) {
                        this[i.default.options.name.singular].associate(this.sequelize)
                    }
                }
                this.sequelize.sync({alter: true})
            })
        })
    }

    async _initSequelize() {
        //初始化Sequelize
        this.config = await this.config;
        this.sequelize = new Sequelize(this.config.db.database, this.config.db.username, this.config.db.password, {
            host: this.config.db.host,
            port: this.config.db.port,
            dialect: this.config.db.dialect,
            define: {
                timestamps: true,
                freezeTableName: true,
                version: true,
                hooks: {
                    beforeFind: async (options) => {
                        // 全局设置默认查询配置

                        if (!options.order) {
                            options.order = [];
                        }
                        if (!options.where) {
                            options.where = {}
                        }

                        // 默认createdAt降序
                        let findOptions = [['createdAt', 'DESC']];
                        options.order = [...findOptions, ...options.order];
                        options.order = [...new Map(options.order)];

                        //分页配置
                        if (!options.where.limit) {
                            options.where.limit = 10;
                        }
                        if (!options.where.offset) {
                            options.where.offset = 0;
                        }
                        options.limit = Number(options.where.limit);
                        options.offset = Number(options.where.offset);
                        delete options.where.limit;
                        delete options.where.offset;
                    }
                }
            }
        });
    }
}

export default new model()